// 设置页面组件

import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { FiVolume2, FiVolumeX, FiTrash2, FiDownload, FiGlobe, FiMoon, FiSun } from 'react-icons/fi';
import { useApp } from '../contexts/AppContext';
import { storageManager } from '../utils/storage';
import { speechService } from '../utils/speechService';
import AIStatus from './AIStatus';
import { toast } from 'react-hot-toast';

const Settings: React.FC = () => {
  const { state, dispatch } = useApp();
  const [settings, setSettings] = useState(storageManager.getSettings());
  const [showConfirmReset, setShowConfirmReset] = useState(false);

  // 切换语音开关
  const toggleVoice = () => {
    dispatch({ type: 'TOGGLE_VOICE' });
    const newSettings = { ...settings, voiceEnabled: !state.voiceEnabled };
    setSettings(newSettings);
    storageManager.saveSettings(newSettings);
    
    toast.success(state.voiceEnabled ? '语音已关闭' : '语音已开启');
  };

  // 清空所有数据
  const resetAllData = () => {
    if (showConfirmReset) {
      storageManager.clearAllData();
      dispatch({ type: 'RESET_STATE' });
      setShowConfirmReset(false);
      toast.success('所有数据已清空');
    } else {
      setShowConfirmReset(true);
      setTimeout(() => setShowConfirmReset(false), 5000);
    }
  };

  // 导出数据
  const exportData = () => {
    const data = {
      userProgress: state.userProgress,
      savedScenes: state.savedScenes,
      learnedWords: storageManager.getLearnedWords(),
      settings: settings,
      exportDate: new Date().toISOString()
    };
    
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `sceneLingo-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    toast.success('数据已导出');
  };

  // 测试语音
  const testVoice = async () => {
    if (!speechService.isSupported()) {
      toast.error('您的浏览器不支持语音功能');
      return;
    }
    
    try {
      await speechService.speak('Hello, this is a voice test.');
      toast.success('语音测试成功');
    } catch (error) {
      toast.error('语音测试失败');
    }
  };

  const settingsSections = [
    {
      title: '学习偏好',
      items: [
        {
          label: '语音交互',
          description: '启用语音朗读和发音练习功能',
          icon: state.voiceEnabled ? FiVolume2 : FiVolumeX,
          action: (
            <button
              onClick={toggleVoice}
              className={`relative inline-flex h-7 w-12 items-center rounded-full transition-all duration-300 shadow-lg ${
                state.voiceEnabled 
                  ? 'bg-gradient-to-r from-indigo-500 via-purple-600 to-pink-500 shadow-purple-200' 
                  : 'bg-gradient-to-r from-gray-300 to-gray-400 shadow-gray-200'
              }`}
            >
              <span
                className={`inline-block h-5 w-5 transform rounded-full bg-white transition-all duration-300 shadow-md ${
                  state.voiceEnabled ? 'translate-x-6 scale-110' : 'translate-x-1'
                }`}
              />
            </button>
          )
        }
      ]
    },
    {
      title: 'AI 服务状态',
      items: [
        {
          label: 'DeepSeek 智能引擎',
          description: '场景生成和词汇解析服务连接状态',
          icon: FiGlobe,
          action: <AIStatus />
        }
      ]
    },
    {
      title: '数据管理',
      items: [
        {
          label: '学习数据导出',
          description: '将您的学习进度和成就导出到本地',
          icon: FiDownload,
          action: (
            <button
              onClick={exportData}
              className="px-3 sm:px-5 py-2 bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-600 text-white rounded-xl font-medium text-xs sm:text-sm hover:shadow-xl hover:scale-105 hover:-translate-y-0.5 transition-all duration-300 whitespace-nowrap"
            >
              导出
            </button>
          )
        },
        {
          label: '重置学习数据',
          description: '清除所有学习记录和偏好设置（不可恢复）',
          icon: FiTrash2,
          action: (
            <button
              onClick={resetAllData}
              className={`px-3 sm:px-5 py-2 rounded-xl font-medium text-xs sm:text-sm transition-all duration-300 transform whitespace-nowrap ${
                showConfirmReset 
                  ? 'bg-gradient-to-r from-red-500 via-pink-500 to-red-600 text-white shadow-xl scale-105 hover:scale-110'
                  : 'bg-gradient-to-r from-red-100 via-pink-100 to-red-200 text-red-600 hover:from-red-200 hover:to-pink-200 hover:shadow-lg hover:scale-105'
              }`}
            >
              {showConfirmReset ? '确认' : '重置'}
            </button>
          )
        }
      ]
    },
    {
      title: '关于 SceneLingo',
      items: [
        {
          label: 'SceneLingo',
          description: '场景化英语学习新体验 - v1.0.0',
          icon: FiGlobe,
          action: (
            <span className="text-sm text-gray-500 font-medium">v1.0.0</span>
          )
        }
      ]
    }
  ];

  return (
    <div className="max-w-2xl mx-auto p-4 sm:p-6 space-y-4 sm:space-y-6">
      {/* 页面标题 */}
      <motion.div 
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        className="text-center space-y-2"
      >
        <h1 className="text-2xl sm:text-3xl font-bold bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-600 bg-clip-text text-transparent">
          个性化设置
        </h1>
        <p className="text-gray-600 text-sm sm:text-base">自定义您的 SceneLingo 学习体验</p>
      </motion.div>

      {/* 设置分组 */}
      {settingsSections.map((section, sectionIndex) => (
        <motion.div
          key={section.title}
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: sectionIndex * 0.1 }}
          className="bg-white rounded-xl shadow-lg overflow-hidden"
        >
          <div className="px-6 py-4 border-b border-gray-100">
            <h2 className="text-lg font-semibold text-gray-800">{section.title}</h2>
          </div>
          
          <div className="divide-y divide-gray-100">
            {section.items.map((item, itemIndex) => {
              const Icon = item.icon;
              
              return (
                <div key={itemIndex} className="px-4 sm:px-6 py-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-0">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-gray-100 rounded-lg flex-shrink-0">
                      <Icon size={16} className="text-gray-600" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <h3 className="font-medium text-gray-800">{item.label}</h3>
                      <p className="text-sm text-gray-500 break-words">{item.description}</p>
                    </div>
                  </div>
                  <div className="flex justify-end sm:justify-start">{item.action}</div>
                </div>
              );
            })}
          </div>
        </motion.div>
      ))}

      {/* 语音测试 */}
      {state.voiceEnabled && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="bg-white rounded-xl shadow-lg p-4 sm:p-6"
        >
          <h3 className="text-lg font-semibold text-gray-800 mb-4">语音功能测试</h3>
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 sm:gap-0">
            <div className="flex-1">
              <p className="text-gray-600 text-sm sm:text-base">测试 SceneLingo 语音交互功能</p>
              <p className="text-xs sm:text-sm text-gray-500 mt-1">点击播放英语发音示例</p>
            </div>
            <button
              onClick={testVoice}
              className="px-4 sm:px-6 py-2.5 sm:py-3 bg-gradient-to-r from-indigo-500 via-purple-600 to-pink-500 text-white rounded-xl font-semibold hover:shadow-xl hover:scale-105 hover:-translate-y-0.5 transition-all duration-300 flex items-center justify-center gap-2 text-sm sm:text-base whitespace-nowrap"
            >
              <FiVolume2 size={16} className="sm:w-[18px] sm:h-[18px]" />
              测试语音
            </button>
          </div>
        </motion.div>
      )}

      {/* 确认删除提示 */}
      {showConfirmReset && (
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          className="bg-red-50 border border-red-200 rounded-xl p-4"
        >
          <div className="flex items-center gap-2 text-red-600 mb-2">
            <FiTrash2 size={16} />
            <span className="font-medium text-sm sm:text-base">确认删除所有数据？</span>
          </div>
          <p className="text-xs sm:text-sm text-red-600 mb-3">
            此操作将永久删除您的所有学习记录、进度和设置，且无法恢复。
          </p>
          <div className="flex gap-2 sm:gap-3">
            <button
              onClick={() => setShowConfirmReset(false)}
              className="flex-1 px-3 sm:px-4 py-2 sm:py-2.5 bg-gradient-to-r from-gray-100 to-gray-200 text-gray-700 rounded-xl font-medium hover:from-gray-200 hover:to-gray-300 hover:shadow-md transition-all duration-300 text-sm sm:text-base"
            >
              取消
            </button>
            <button
              onClick={resetAllData}
              className="flex-1 px-3 sm:px-4 py-2 sm:py-2.5 bg-gradient-to-r from-red-500 via-pink-500 to-red-600 text-white rounded-xl font-semibold hover:shadow-xl hover:scale-105 transition-all duration-300 text-sm sm:text-base"
            >
              确认删除
            </button>
          </div>
        </motion.div>
      )}

      {/* 版权信息 */}
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.5 }}
        className="text-center text-sm text-gray-500"
      >
        <p className="flex items-center justify-center gap-2">
          <span>由</span>
          <span className="font-semibold text-transparent bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text">SceneLingo Team</span>
          <span>精心打造</span>
        </p>
        <p className="mt-2 text-xs">让英语学习更有趣，让知识获得更轻松</p>
      </motion.div>
    </div>
  );
};

export default Settings;